/**
 * [一句话描述该类的功能]
 *
 * @author : [kai]
 * @version : [v1.0]
 * @createTime : [2022/10/28 19:29]
 */


package com.find.controller;

import com.find.controller.utils.R;
import com.find.domain.User;
import com.find.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@RestController
@Api(tags="注册")
@RequestMapping("/register")
public class RegisterController {
    @Value("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$")
    String reg;
    @Value("^[a-zA-Z0-9_]{4,16}$")
    String nameReg;
    @Autowired
    private UserService userService;
    @PostMapping
    public R login(@RequestBody Map<String,Object> users
            , HttpServletResponse response)throws IOException {
        response.setStatus(500);
        if(users.containsKey("rePassword")&&(!users.get("password").toString().equals(users.get("rePassword").toString()))){
            return new R(false,"两次密码不一致");
        }
        if(users.get("name") == null|| "".equals(users.get("name"))){
            response.setStatus(500);
            return new R(false,"用户名不能为空");
        }

        if(users.get("password") == null||"".equals(users.get("password").toString())){
            response.setStatus(500);
            return new R(false,"用户密码不能为空");
        };
        if(!users.get("name").toString().matches(nameReg)){
            response.setStatus(500);
            return new R(false,"用户名不符合规则");
        };
        if(!users.get("password").toString().matches(reg)){
            response.setStatus(500);
            return new R(false,"密码不符合规则");
        };
        User user=new User(users.get("name").toString(),users.get("password").toString());
        boolean flag=userService.saveUser(user);
        Cookie uidCookie = new Cookie("newUid",user.getId().toString());
        uidCookie.setPath("/");
        uidCookie.setMaxAge(60*60*24*30);
        response.addCookie(uidCookie);
        if(!flag){
            response.setStatus(500);
            return new R(false,"注册失败");
        }
        else {
            response.setStatus(200);
            return new R(true, "注册成功");
        }
    }
}
